<?php

namespace app\common\library;

use Exception;
use support\Redis;

/**
 * 操作次数限制
 */
class ActionTimes
{
    /**
     * Notes:操作次数限制
     * @param $key
     * @param int $times
     * @param int $ttl
     * @param string $msg
     * @throws Exception
     */
    public static function times($key, int $times=10, int $ttl=300, string $msg="操作异常，请稍后重试"): void
    {
        $key = RedisKey::actionTimes(str_replace(".", "_", getCdnRealIp()).'_'.$key);
        $actionTimes = Redis::get($key)?:0;
        if($actionTimes >= $times){
            throw new Exception($msg);
        }
        $actionTimes++;
        Redis::setEx($key, $ttl, $actionTimes);
    }

}